package com.l024.meet.ui;

import android.os.Bundle;
import android.view.View;
import android.view.ViewStub;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.l024.framework.adapter.CommonAdapter;
import com.l024.framework.adapter.CommonViewHolder;
import com.l024.framework.bmob.BmobManager;
import com.l024.framework.bmob.IMUser;
import com.l024.framework.cloud.CloudManager;
import com.l024.framework.db.LitePalHelper;
import com.l024.framework.db.NewFriend;
import com.l024.framework.event.EventBusManager;
import com.l024.framework.utils.CommonUtils;
import com.l024.framework.utils.Logutils;
import com.l024.meet.R;

import java.util.ArrayList;
import java.util.List;

import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.FindListener;
import cn.bmob.v3.listener.SaveListener;
import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

public class NewFriendActivity extends AppCompatActivity {

    private View itemEmptyView;
    private RecyclerView mNewFriendView;
    private Disposable disposable;

    private List<NewFriend> friends = new ArrayList<>();

    private CommonAdapter<NewFriend> commonAdapter;
    //对方好友
    private IMUser imUser;

    /**
     * 1.查询好友的申请列表
     * 2.通过适配器显示
     * 3.如果同意添加则加对方为自己好友
     * 4.发送自定义消息给对方
     * 5.对方将自己加入好友列表
     *
     * @param savedInstanceState
     */
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_new_friend);
        initView();
    }

    private void initView() {
        itemEmptyView = findViewById(R.id.item_empty_view);
        mNewFriendView = (RecyclerView) findViewById(R.id.mNewFriendView);
        //查询好友列表
        queryNewFriend();
        //线性布局
        mNewFriendView.setLayoutManager(new LinearLayoutManager(this));
        //垂直
        mNewFriendView.addItemDecoration(new DividerItemDecoration(this,DividerItemDecoration.VERTICAL));
        //初始化适配器
        commonAdapter = new CommonAdapter<NewFriend>(friends, new CommonAdapter.OnBindDataListener<NewFriend>() {
            @Override
            public void onBindViewHolder(NewFriend model, CommonViewHolder commonViewHolder, int type, int position) {
                //根据id查询用户信息
                BmobManager.getInstance().queryObjectIdFriend(model.getUserId(), new FindListener<IMUser>() {
                    @Override
                    public void done(List<IMUser> list, BmobException e) {
                        //填充属性
                        if(e==null){
                            if(CommonUtils.isEmpty(list)){
                                imUser = list.get(0);
                                commonViewHolder.setImageUrl(NewFriendActivity.this,R.id.iv_photo,imUser.getPhoto());
                                commonViewHolder.setImageResource(R.id.iv_sex,imUser.isSex()?R.drawable.img_boy_icon:R.drawable.img_girl_icon);
                                commonViewHolder.setText(R.id.tv_nickname,imUser.getNickName());
                                commonViewHolder.setText(R.id.tv_desc,imUser.getDesc());
                                commonViewHolder.setText(R.id.tv_msg,model.getMsg());
                                commonViewHolder.setText(R.id.tv_age,imUser.getAge()+getString(R.string.text_search_age));

                                if(model.getIsAgree()==0){
                                    commonViewHolder.getView(R.id.ll_agree).setVisibility(View.GONE);
                                    commonViewHolder.getView(R.id.tv_result).setVisibility(View.VISIBLE);
                                    commonViewHolder.setText(R.id.tv_result,"已同意");
                                }else if(model.getIsAgree()==1){
                                    commonViewHolder.getView(R.id.ll_agree).setVisibility(View.GONE);
                                    commonViewHolder.getView(R.id.tv_result).setVisibility(View.VISIBLE);
                                    commonViewHolder.setText(R.id.tv_result,"已拒绝");
                                }
                            }else{
                                Logutils.e("查询用户id失败:id"+model.getUserId());
                            }
                        }else{
                            Logutils.e("查询用户id失败:id"+model.getUserId()+"  错误信息:"+e);
                        }
                    }
                });
                //添加点击事件
                //同意添加
                commonViewHolder.getView(R.id.ll_yes).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        /**
                         * 1.同意则刷新当前item
                         * 2.将好友添加到自己好友列表
                         * 3.通知对方我同意
                         * 4.对方将我添加好友
                         * 5.刷新好友列表
                         */
                        updateItem(position,0);
                        BmobManager.getInstance().addFriend(imUser, new SaveListener<String>() {
                            @Override
                            public void done(String s, BmobException e) {
                                if(e==null){
                                    Logutils.i("添加好友成功"+s);
                                    Toast.makeText(NewFriendActivity.this, "添加好友成功", Toast.LENGTH_SHORT).show();
                                    //通知对方添加成功
                                    CloudManager.getInstance().sendAddFrientMessage("",CloudManager.TYPE_AGREED_FRIEND,imUser.getObjectId());
                                    //更新自己的好友列表
                                    EventBusManager.post(EventBusManager.FLAY_UPDATE_FRIEND_LIST);
                                }else {
                                    Logutils.e("添加好友失败："+e);
                                    Toast.makeText(NewFriendActivity.this, "添加好友失败："+e, Toast.LENGTH_SHORT).show();
                                }
                            }
                        });
                    }
                });
                //拒绝添加
                commonViewHolder.getView(R.id.ll_no).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        updateItem(position,0);
                    }
                });
            }

            @Override
            public int getLayoutId(int type) {
                return R.layout.layout_new_friend_item;
            }
        });
        mNewFriendView.setAdapter(commonAdapter);
    }

    /**
     * 查询添加好友列表
     */
    private void queryNewFriend(){
        /**
         * 在子线程中获取好友申请列表，在主线程中更新ui
         * Rxjava的线程调度
         */
        disposable = Observable.create(new ObservableOnSubscribe<List<NewFriend>>() {
            @Override
            public void subscribe(ObservableEmitter<List<NewFriend>> emitter) throws Exception {
                //执行子线程操作
                emitter.onNext(LitePalHelper.getInstance().queryNewFriend());
                emitter.onComplete();
            }
            //切换线程
        }).subscribeOn(Schedulers.newThread())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(new Consumer<List<NewFriend>>() {
                @Override
                public void accept(List<NewFriend> newFriends) throws Exception {
                    //返回结果更新ui
                    if(CommonUtils.isEmpty(newFriends)){
                        itemEmptyView.setVisibility(View.GONE);
                        mNewFriendView.setVisibility(View.VISIBLE);
                        friends.addAll(newFriends);
                        //刷新数据
                        commonAdapter.notifyDataSetChanged();
                    }else{
                        itemEmptyView.setVisibility(View.VISIBLE);
                        mNewFriendView.setVisibility(View.GONE);
                    }
                }
            });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //如果还在执行，则解绑
        if(disposable.isDisposed()){
            disposable.dispose();
        }
    }

    /**
     * 更新item
     * @param position
     * @param i
     */
    private void updateItem(int position,int i){
        NewFriend newFriend = friends.get(position);
        //更新数据库
        LitePalHelper.getInstance().updateNewFriend(newFriend.getUserId(),i);
        //更新本地数据源
        newFriend.setIsAgree(i);
        friends.set(position,newFriend);
        //更新视图
        commonAdapter.notifyDataSetChanged();
    }
}
